package com.nanhu.sms.adapter;

import java.util.ArrayList;
import com.nanhu.sms.R;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

public class CheckBoxCursorAdapter extends SimpleCursorAdapter{
	
	private ArrayList<Selection> selections = new ArrayList<Selection>();

	public CheckBoxCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, ArrayList<Selection> selection) {
		super(context, layout, c, from, to, 0);
		if(selection != null)
			this.selections = selection;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = super.getView(position, convertView, parent);
		CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkBox);
		TextView text = (TextView)view.findViewById(R.id.text);
		String number = text.getText().toString();
		TextView title = (TextView)view.findViewById(R.id.title);
		String name = title.getText().toString();
		Selection selection = new Selection(number, name);
		checkBox.setTag(selection);
		if(selections != null && selections.indexOf(selection) != -1){
			checkBox.setChecked(true);
		}else{
			checkBox.setChecked(false);
		}
		return view;
	};
	
	public ArrayList<Selection> getSelectedItems(){
        return selections;  
    }
	
	public void onCheckChange(CheckBox checkBox){
		Selection selection = (Selection)checkBox.getTag();
		if(checkBox.isChecked()){
			selections.add(selection);
		}else{
			selections.remove(selection);
		}
	}
	
	public static class Selection{
		
		public String number;
		
		public String name;
		
		public Selection(String number, String name){
			this.number = number;
			this.name = name;
		}
		
		@Override
		public boolean equals(Object o) {
			if(o instanceof Selection){
				Selection s = (Selection)o;
				if(!this.number.equals(s.number))
					return false;
				if(!this.name.equals(s.name))
					return false;
			}else{
				return false;
			}
			return true;
		}
	}
}
